<template>
	<transition :name="name">
		<div class="j-dropdown" v-show="status" @click="onDropDownContentClick">
			<label class="hidden">
				<input type="text" v-model="status" class="form-control"/>
			</label>
			<slot/>
		</div>
	</transition>
</template>

<script>
	/* eslint-disable no-undef */
	let dropDowns = [];
	export default {
		name: 'DropDown',
		data () {
			return {
				status: this.value
			};
		},
		props: {
			value: {type: Boolean, default: false},
			name: {type: String, default: 'bounce'},
			id: {type: String, required: true}
		},
		methods: {
			hide () {
				if (this.status === true) {
					this.status = false;
				}
			},
			unbind (id) {
				$(`[data-togger="dropdown"][data-target="${id}"]`).unbind('click');
			},
			bind (id) {
				if (id === 'null') {
					return;
				}
				$(`[data-togger="dropdown"][data-target="${id}"]`).on('click', (e) => {
					e.stopPropagation();
					if (this.status === false) {
						this.hideAll();
						this.$emit('DropDown:show');
						this.status = true;
					} else {
						this.$emit('DropDown:hide');
						this.hide();
					}
				});
			},
			removeDocumentEvent () {
				document.documentElement.removeEventListener('click', this.hide, false);
			},
			addDocumentEvent () {
				document.documentElement.addEventListener('click', this.hide, false);
			},
			onDropDownContentClick (event) {
				event.stopPropagation();
			},
			hideAll () {
				if (dropDowns && dropDowns.length) {
					for (let i = 0; i < dropDowns.length; i++) {
						let dropDown = dropDowns[i];
						dropDown.$emit('DropDown:hide');
						dropDown.status = false;
					}
				}
			}
		},
		watch: {
			value: function (newVal) {
				this.status = newVal;
			},
			status: function (newVal) {
				this.$emit('input', newVal);
			},
			id: function (newVal, oldVal) {
				this.unbind(oldVal);
				this.bind(newVal);
			}
		},
		mounted () {
			this.bind(this.id);
			this.$on('DropDown:show', () => {
				this.addDocumentEvent();
			});
			this.$on('DropDown:hide', () => {
				this.removeDocumentEvent();
			});
			dropDowns.push(this);
		}
	};
</script>
